<template>
  <div class="employee-products">
    <el-card>
      <template #header>
        <div class="header-bar">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索商品名称或条形码"
            clearable
            style="width: 280px"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          
          <el-select 
            v-model="categoryId" 
            placeholder="选择分类" 
            clearable
            style="width: 200px"
            @change="handleSearch"
          >
            <el-option label="全部分类" :value="null" />
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="(category.icon || '📦') + ' ' + category.name"
              :value="category.id"
            >
              <span>{{ category.icon || '📦' }} {{ category.name }}</span>
              <span style="color: #8492a6; font-size: 13px; margin-left: 8px;">({{ category.productCount || 0 }})</span>
            </el-option>
          </el-select>
          
          <el-select 
            v-model="stockStatus" 
            placeholder="库存预警" 
            clearable
            style="width: 150px"
            @change="handleSearch"
          >
            <el-option label="全部" :value="null" />
            <el-option label="库存预警" value="warning" />
          </el-select>
          
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon> 查询
          </el-button>
          
          <el-button @click="handleReset">
            <el-icon><RefreshLeft /></el-icon> 重置
          </el-button>
        </div>
      </template>
      
      <el-table v-loading="loading" :data="productList" border>
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column label="商品图片" width="100">
          <template #default="{ row }">
            <img :src="getImageUrl(row.image)" style="width: 60px; height: 60px; object-fit: cover; border-radius: 4px;" />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="商品名称" />
        <el-table-column prop="categoryName" label="分类" width="140">
          <template #default="{ row }">
            <el-tag>{{ row.categoryIcon || '📦' }} {{ row.categoryName }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格" width="100">
          <template #default="{ row }">
            <span class="price">¥{{ row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="100">
          <template #default="{ row }">
            <el-tag :type="row.stock < 10 ? 'danger' : 'success'">
              {{ row.stock }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="barcode" label="条形码" width="150" />
        <el-table-column label="操作" width="100">
          <template #default="{ row }">
            <el-button type="primary" text @click="viewDetail(row)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <el-pagination
        v-if="total > 0"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        style="margin-top: 20px; justify-content: center;"
        @size-change="loadProducts"
        @current-change="loadProducts"
      />
    </el-card>
    
    <!-- 详情对话框 -->
    <el-dialog v-model="detailVisible" title="商品详情" width="600px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="商品ID">{{ currentProduct.id }}</el-descriptions-item>
        <el-descriptions-item label="商品名称">{{ currentProduct.name }}</el-descriptions-item>
        <el-descriptions-item label="分类">{{ currentProduct.categoryName }}</el-descriptions-item>
        <el-descriptions-item label="价格">¥{{ currentProduct.price }}</el-descriptions-item>
        <el-descriptions-item label="库存">{{ currentProduct.stock }}</el-descriptions-item>
        <el-descriptions-item label="条形码">{{ currentProduct.barcode }}</el-descriptions-item>
        <el-descriptions-item label="描述" :span="2">{{ currentProduct.description || '-' }}</el-descriptions-item>
      </el-descriptions>
      
      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getProductList } from '@/api/product'
import { getCategoryList } from '@/api/category'
import { ElMessage } from 'element-plus'
import { Search, RefreshLeft } from '@element-plus/icons-vue'

const loading = ref(false)
const searchKeyword = ref('')
const categoryId = ref(null)
const stockStatus = ref(null)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const productList = ref([])
const categories = ref([])

const detailVisible = ref(false)
const currentProduct = ref({})

onMounted(() => {
  loadCategories()
  loadProducts()
})

const loadCategories = async () => {
  try {
    const res = await getCategoryList()
    if (res.code === 200 && res.data) {
      // 只显示启用状态的分类
      categories.value = res.data.filter(cat => cat.status === 1)
    }
  } catch (error) {
    console.error('加载分类失败:', error)
  }
}

const loadProducts = async () => {
  loading.value = true
  try {
    // 构建请求参数
    const requestData = {
      page: currentPage.value,
      pageSize: pageSize.value,
      name: searchKeyword.value || null,
      categoryId: categoryId.value || null,
      status: 1  // 只查询上架商品
    }
    
    // 根据库存状态筛选
    if (stockStatus.value === 'warning') {
      // 库存预警：库存小于等于最低库存
      requestData.stockAlert = true
    } else if (stockStatus.value === 'low') {
      // 库存不足：这里暂时也使用库存预警的逻辑
      // TODO: 后端需要支持更精确的库存筛选
      requestData.stockAlert = true
    }
    // normal状态不添加库存筛选
    
    const res = await getProductList(requestData)
    if (res.code === 200 && res.data) {
      productList.value = res.data.records || []
      total.value = res.data.total || 0
      
      // 添加分类图标（如果有分类数据）
      productList.value = productList.value.map(product => {
        const category = categories.value.find(cat => cat.id === product.categoryId)
        return {
          ...product,
          categoryIcon: category?.icon || '📦'
        }
      })
    }
  } catch (error) {
    console.error('加载商品列表失败:', error)
    ElMessage.error('加载商品列表失败')
    // 使用模拟数据
    productList.value = Array.from({ length: 10 }, (_, i) => ({
      id: i + 1,
      name: `商品${i + 1}`,
      categoryName: '饮料',
      categoryIcon: '🥤',
      price: (Math.random() * 50 + 5).toFixed(2),
      image: 'https://via.placeholder.com/60',
      stock: Math.floor(Math.random() * 100),
      barcode: `69012345${String(i).padStart(5, '0')}`,
      description: '优质商品，值得信赖'
    }))
    total.value = 100
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  loadProducts()
}

const handleReset = () => {
  searchKeyword.value = ''
  categoryId.value = null
  stockStatus.value = null
  currentPage.value = 1
  loadProducts()
}

const viewDetail = (product) => {
  currentProduct.value = product
  detailVisible.value = true
}

// 获取图片URL（处理相对路径和绝对路径）
const getImageUrl = (url) => {
  if (!url) return 'https://via.placeholder.com/60'
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url
  }
  return 'http://localhost:8080' + url
}
</script>

<style lang="scss" scoped>
.employee-products {
  .header-bar {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    align-items: center;
  }
  
  .price {
    color: #ff4d4f;
    font-weight: bold;
  }
}
</style>











